package com.zt.dev.userManage.controller;

import com.zt.dev.common.ServerResponse;
import com.zt.dev.semiPhysicalEquipment.util.PageBean;
import com.zt.dev.simulationModel.utils.ExcelUtil;
import com.zt.dev.userManage.entity.dto.UserAndTask;
import com.zt.dev.userManage.entity.enumvo.RoleEnum;
import com.zt.dev.userManage.entity.vo.User;
import com.zt.dev.userManage.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class UserManageController {

    @Autowired
    private UserService userService;

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    @RequestMapping("/insertUser")
    @ResponseBody
    public ServerResponse insertUser(User user){
        if(user != null){
            int result = userService.insertUser(user);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("用户注册成功");
            }else{
                return ServerResponse.createByErrorMessage("用户已存在");
            }
        }
        return ServerResponse.createByErrorMessage("新增用户信息为空");
    }

    /**
     * 通过id，多删除用户
     * @param ids
     * @return
     */
    @RequestMapping("/deleteById")
    @ResponseBody
    public ServerResponse deleteById(Integer[] ids){
        if(ids.length > 0 ){
            int result = userService.deleteById(ids);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("用户信息删除成功");
            }else{
                return ServerResponse.createByErrorMessage("删除失败");
            }
        }
        return ServerResponse.createByErrorMessage("参数为空");
    }

    /**
     * 通过用户名查询用户信息
     * @param userName
     * @return
     */
    @RequestMapping("/getUserByName")
    @ResponseBody
    public ServerResponse getUserByName(String userName){
        if(userName != null){
            List<User> userList = userService.getUserByName(userName);
            if(userList != null){
                return ServerResponse.createBySuccess(userList);
            }else{
                return ServerResponse.createByErrorMessage("查询失败");
            }
        }
        return ServerResponse.createByErrorMessage("用户名为空");
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @RequestMapping("/updateUserById")
    @ResponseBody
    public ServerResponse updateUserById(User user){
        if(user != null){
            int result = userService.updateUserById(user);
            if(result > 0){
                return ServerResponse.createBySuccessMessage("修改成功");
            }else{
                return ServerResponse.createByErrorMessage("信息修改失败");
            }
        }
        return ServerResponse.createByErrorMessage("用户参数为空");
    }

    /**
     * 分页查询人员列表
     * @return
     */
    @RequestMapping("/getAllUser")
    @ResponseBody
    public ServerResponse getTable( PageBean pageBean,String userName) {
        PageBean<User> userList = userService.getAllUser(pageBean.getCurrentPage(), pageBean.getPageSize(),userName);
        if(userList.getLists().size() != 0){
            return  ServerResponse.createBySuccess(userList);
        }
        return ServerResponse.createByErrorMessage("查询为空");
    }


    /**
     * 通过id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    public ServerResponse getUserById(Integer id){
        if(id != null){
            User user = userService.getUserById(id);
            if(user != null){
                return ServerResponse.createBySuccess(user);
            }else{
                return ServerResponse.createByErrorMessage("用户不存在");
            }
        }
        return ServerResponse.createByErrorMessage("查询参数为空");
    }

    /**
     * 通过id查询用户信息
     * @param role
     * @return
     */
    @RequestMapping("/getUserByRole")
    @ResponseBody
    public ServerResponse getUserByRole(Integer role){
        if(role != null){
            List<User> userList = userService.getUserByRole(role);
            if(userList != null){
                return ServerResponse.createBySuccess(userList);
            }else{
                return ServerResponse.createByErrorMessage("用户不存在");
            }
        }
        return ServerResponse.createByErrorMessage("查询参数为空");
    }

    /**
     * 导入人员信息
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/importFile")
    @ResponseBody
    public ServerResponse importFile(@RequestParam("file") MultipartFile file) throws IOException {
        if(file == null){
            return ServerResponse.createByErrorMessage("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        List<User> userList = null;
        //处理excel文件
        if (".xls".equals(fileType) || ".xlsx".equals(fileType)) {
            userList= userService.uploadFileExcel(file);
        }else if(".txt".equals(fileType)){
            // result = userService.uploadFileTxt(file);
        }
        if(userList != null){
            return ServerResponse.createBySuccess(userList);
        }
        return ServerResponse.createByErrorMessage("文件导入失败");
    }

    /**
     * 导出文件
     * @return
     */
    @GetMapping("/exportFile")
    @ResponseBody
    public void exportFile(@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime,HttpServletResponse response) throws Exception {
        String fileName = "人员信息表" + ".xls";
        List<UserAndTask> userList = userService.getUserByTime(startTime, endTime);
        String[] title1 = new String[]{"序号,1,2"};
        String[] title2 = new String[]{"用户名", "姓名", "性别", "角色", "职称","单位","专业","联系方式","创建时间"};
        String[] column = new String[]{"userName", "realName", "gendar", "roleName", "profession","unit","major","tel","createTime"};
        HSSFWorkbook wb = new ExcelUtil().getHSSFWorkbook(fileName,title1,title2,userList,column);
        fileName = new String(fileName.getBytes(),"ISO8859-1");
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        response.addHeader("Pargam","no-cache");
        response.addHeader("Cache-Control","no-cache");
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

}
